package com.sgai.zero_robot.ui.history;


import static com.sgai.zero_robot.utils.ZeroUtils.getInstall;

import com.sgai.zero_robot.database.ZeroDetectionEntity;
import com.sgai.zero_robot.pojo.InstallInfo;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.TableRowAlign;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGrid;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGridCol;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class ExportRunnable implements Runnable {
    private final RunnableCallBack<String> callBack;
    private final InstallInfo installInfo;
    private final String rootFilePath;
    List<Integer> sb1 = new ArrayList<>();
    List<Integer> sb2 = new ArrayList();
    List<Integer> sb3 = new ArrayList();
    List<Integer> sb4 = new ArrayList();
    List<Integer> sb5 = new ArrayList();
    List<Integer> sb6 = new ArrayList();
    List<Integer> sb7 = new ArrayList();
    List<Integer> sb8 = new ArrayList();
    List<Integer> sb9 = new ArrayList();
    public ExportRunnable( InstallInfo installInfo,String rootFilePath, RunnableCallBack<String> callBack){
        this.callBack=callBack;
        this.installInfo=installInfo;
        this.rootFilePath=rootFilePath;
    }
    private String getCollect(StringBuilder sb){
        if (sb.toString().isEmpty()){
            return "无";
        }else{
            return sb.toString();
        }
    }
    private void addPosition(List<Integer> list , ZeroDetectionEntity zeroDetectionEntity){
       if (zeroDetectionEntity.getState() == 0){
           list.add(zeroDetectionEntity.getPosition());
       }
    }
    @Override
    public void run() {
        if (installInfo == null){
            if (callBack!=null){
                callBack.onResult(null);
            }
            return;
        }

         String DOCUMENT_TITLE = installInfo.lineName+"#"+ installInfo.towerName+"塔-"+getInstall(installInfo.install)+"绝缘子检测报告";

        // 模拟表格数据，可根据实际从数据库等获取
        List<List<String>> TABLE_DATA = new ArrayList<>();
        //到这里 应该会有9个列表 每个列表的长度相等
        List<ZeroDetectionEntity> one = installInfo.phaseInfos.get(0).insulatorInfos.get(0).insulatorInfos;
        List<ZeroDetectionEntity> two = installInfo.phaseInfos.get(0).insulatorInfos.get(1).insulatorInfos;
        List<ZeroDetectionEntity> three = installInfo.phaseInfos.get(0).insulatorInfos.get(2).insulatorInfos;

        List<ZeroDetectionEntity> four = installInfo.phaseInfos.get(1).insulatorInfos.get(0).insulatorInfos;
        List<ZeroDetectionEntity> five = installInfo.phaseInfos.get(1).insulatorInfos.get(1).insulatorInfos;
        List<ZeroDetectionEntity> six = installInfo.phaseInfos.get(1).insulatorInfos.get(2).insulatorInfos;

        List<ZeroDetectionEntity> seven = installInfo.phaseInfos.get(2).insulatorInfos.get(0).insulatorInfos;
        List<ZeroDetectionEntity> eight = installInfo.phaseInfos.get(2).insulatorInfos.get(1).insulatorInfos;
        List<ZeroDetectionEntity> nine = installInfo.phaseInfos.get(2).insulatorInfos.get(2).insulatorInfos;
        for (int i = 0;i<one.size();i++){
            List<String> rowContent = new ArrayList<>(10);
            rowContent.add(String.valueOf(i+1));
            rowContent.add(getState(one.get(i).getState()));
            rowContent.add(getState(two.get(i).getState()));
            rowContent.add(getState(three.get(i).getState()));
            rowContent.add(getState(four.get(i).getState()));
            rowContent.add(getState(five.get(i).getState()));
            rowContent.add(getState(six.get(i).getState()));
            rowContent.add(getState(seven.get(i).getState()));
            rowContent.add(getState(eight.get(i).getState()));
            rowContent.add(getState(nine.get(i).getState()));
            TABLE_DATA.add(rowContent);
            addPosition(sb1,one.get(i));
            addPosition(sb2,two.get(i));
            addPosition(sb3,three.get(i));
            addPosition(sb4,four.get(i));
            addPosition(sb5,five.get(i));
            addPosition(sb6,six.get(i));
            addPosition(sb7,seven.get(i));
            addPosition(sb8,eight.get(i));
            addPosition(sb9,nine.get(i));
        }

        generateWordDocument(DOCUMENT_TITLE,TABLE_DATA);
    }
    private String getState(int state){
        if (state <0){
            return "/";
        }else{
            return String.valueOf(state);
        }
    }
    /**
     * 确保行中包含指定数量的单元格
     */
    private static void initializeRowCells(XWPFTableRow row, int cellCount) {
        // 清除默认单元格
        while (row.getTableCells().size() > 0) {
            row.removeCell(0);
        }

        // 创建指定数量的单元格
        for (int i = 0; i < cellCount; i++) {
            row.createCell();
        }
    }

    /**
     * 设置单元格文本并对齐（安全方法）
     */
    private static void setCellTextAndAlignment(XWPFTableCell cell, String text, ParagraphAlignment alignment) {
        if (cell == null) return;

        // 清除现有内容
        while (cell.getParagraphs().size() > 0) {
            cell.removeParagraph(0);
        }

        // 添加新段落并设置文本和对齐方式
        XWPFParagraph para = cell.addParagraph();
        para.setAlignment(alignment);
        para.createRun().setText(text);
    }

    /**
     * 合并表格的水平单元格（优化版）
     */
    private static void mergeCellsHorizontally(XWPFTableRow row, int fromCell, int toCell) {
        if (fromCell >= toCell) return;

        // 确保单元格存在
        ensureRowHasCells(row, toCell);

        // 获取第一个单元格并设置合并跨度
        XWPFTableCell firstCell = row.getCell(fromCell);
        firstCell.getCTTc().addNewTcPr().addNewGridSpan().setVal(BigInteger.valueOf(toCell - fromCell + 1));

        // 从后向前移除多余的单元格（仅移除，不操作）
        for (int i = toCell; i > fromCell; i--) {
            row.removeCell(i);
        }
    }

    /**
     * 合并表格的垂直单元格（优化版）
     */
    private static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
        if (fromRow >= toRow) return;

        // 确保所有行存在
        ensureTableHasRows(table, toRow);

        // 确保每行的目标列单元格存在
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            ensureRowHasCells(table.getRow(rowIndex), col);
        }

        // 设置垂直合并
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            CTVMerge vmerge = cell.getCTTc().addNewTcPr().addNewVMerge();

            if (rowIndex == fromRow) {
                vmerge.setVal(STMerge.RESTART);
            } else {
                vmerge.setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * 确保表格有足够的行
     */
    private static void ensureTableHasRows(XWPFTable table, int rowCount) {
        while (table.getRows().size() <= rowCount) {
            table.createRow();
        }
    }

    /**
     * 确保行有足够的单元格
     */
    private static void ensureRowHasCells(XWPFTableRow row, int cellCount) {
        while (row.getTableCells().size() <= cellCount) {
            row.createCell();
        }
    }
    public void generateWordDocument(String DOCUMENT_TITLE, List<List<String>> TABLE_DATA) {
        XWPFDocument document = new XWPFDocument();
        // 添加标题段落
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun run = titleParagraph.createRun();
        run.setText(DOCUMENT_TITLE);
        run.setBold(true);
        run.setFontSize(16);
        document.createParagraph();

        // 创建表格
        XWPFTable table = document.createTable();
        table.removeRow(0);
        // 设置表格整体宽度为自动适应
        CTTbl tbl = table.getCTTbl();
        CTTblPr tblPr = tbl.getTblPr() != null ? tbl.getTblPr() : tbl.addNewTblPr();
        CTTblWidth tblWidth = tblPr.getTblW() != null ? tblPr.getTblW() : tblPr.addNewTblW();
        tblWidth.setType(STTblWidth.AUTO);
        tblWidth.setW(BigInteger.valueOf(9000));
        table.setTableAlignment(TableRowAlign.CENTER);
        // 初始化表格网格
        CTTblGrid grid = tbl.getTblGrid() != null ? tbl.getTblGrid() : tbl.addNewTblGrid();
        for (int i = 0; i < 10; i++) {
            CTTblGridCol gridCol = grid.addNewGridCol();
            gridCol.setW(BigInteger.valueOf(900));
        }
        XWPFTableRow row0 = table.createRow();
        initializeRowCells(row0, 10);
        mergeCellsHorizontally(row0, 1, 9);
        setCellTextAndAlignment(row0.getCell(0), "地址", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row0.getCell(1), installInfo.province+installInfo.city, ParagraphAlignment.CENTER);

        XWPFTableRow row1 = table.createRow();
        initializeRowCells(row1, 10);
        // 合并
        mergeCellsHorizontally(row1, 7, 9);
        mergeCellsHorizontally(row1, 2, 5);
        setCellTextAndAlignment(row1.getCell(0), "杆塔信息", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row1.getCell(1), "线路", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row1.getCell(2), installInfo.lineName, ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row1.getCell(3), "塔号", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row1.getCell(4), installInfo.towerName, ParagraphAlignment.CENTER);


        // 第二行：安装值
        XWPFTableRow row2 = table.createRow();
        initializeRowCells(row2, 10);
        mergeCellsHorizontally(row2, 1, 9);
        setCellTextAndAlignment(row2.getCell(0), "安装值", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row2.getCell(1), getInstall(installInfo.install), ParagraphAlignment.CENTER);

        XWPFTableRow row3 = table.createRow();
        initializeRowCells(row3, 10);
        mergeCellsHorizontally(row3, 7, 9);
        mergeCellsHorizontally(row3, 4, 6);
        mergeCellsHorizontally(row3, 1, 3);
        setCellTextAndAlignment(row3.getCell(0), "安装相别", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row3.getCell(1), "A相", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row3.getCell(2), "B相", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row3.getCell(3), "C相", ParagraphAlignment.CENTER);
        // 第四行：绝缘子片号及表头
        XWPFTableRow row4 = table.createRow();
        initializeRowCells(row4, 10);
        setCellTextAndAlignment(row4.getCell(0), "绝缘子片号", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row4.getCell(1), "外串", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row4.getCell(2), "中串", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row4.getCell(3), "内串", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row4.getCell(4), "外串", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row4.getCell(5), "中串", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row4.getCell(6), "内串", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row4.getCell(7), "外串", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row4.getCell(8), "中串", ParagraphAlignment.CENTER);
        setCellTextAndAlignment(row4.getCell(9), "内串", ParagraphAlignment.CENTER);


//        // 逐行构建表格内容
        for (int j =0;j<TABLE_DATA.size();j++){
            List<String> rowData = TABLE_DATA.get(j);
            XWPFTableRow row = table.createRow();
            initializeRowCells(row, 10);
            setCellTextAndAlignment(row.getCell(0), rowData.get(0), ParagraphAlignment.CENTER);
            setCellTextAndAlignment(row.getCell(1), rowData.get(1), ParagraphAlignment.CENTER);
            setCellTextAndAlignment(row.getCell(2), rowData.get(2), ParagraphAlignment.CENTER);
            setCellTextAndAlignment(row.getCell(3), rowData.get(3), ParagraphAlignment.CENTER);
            setCellTextAndAlignment(row.getCell(4), rowData.get(4), ParagraphAlignment.CENTER);
            setCellTextAndAlignment(row.getCell(5), rowData.get(5), ParagraphAlignment.CENTER);
            setCellTextAndAlignment(row.getCell(6), rowData.get(6), ParagraphAlignment.CENTER);
            setCellTextAndAlignment(row.getCell(7), rowData.get(7), ParagraphAlignment.CENTER);
            setCellTextAndAlignment(row.getCell(8), rowData.get(8), ParagraphAlignment.CENTER);
            setCellTextAndAlignment(row.getCell(9), rowData.get(9), ParagraphAlignment.CENTER);
        }
        document.createParagraph();
        createParagraph(document,sb1,sb2,sb3,sb4,sb5,sb6,sb7,sb8,sb9);


        //检测文件夹是否存在
        File file = new File(rootFilePath);
        if (!file.exists()){
            file.mkdirs();
        }

        // 保存文档到外部存储
        String filePath = rootFilePath +DOCUMENT_TITLE+ ".docx";
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath);
            document.write(out);
            if (callBack!=null){
                callBack.onResult(filePath);
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (callBack!=null){
                callBack.onResult(null);
            }
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void createParagraph(XWPFDocument document, List<Integer> sb1, List<Integer> sb2, List<Integer> sb3, List<Integer> sb4, List<Integer> sb5, List<Integer> sb6, List<Integer> sb7, List<Integer> sb8, List<Integer> sb9) {
        XWPFParagraph collectParagraph = document.createParagraph();
        collectParagraph.setAlignment(ParagraphAlignment.LEFT);
        XWPFRun run = collectParagraph.createRun();
        run.setText("零值汇总:");
        run.setBold(true);
        run.setFontSize(14);

        if (sb1.isEmpty()&&sb2.isEmpty()&&sb3.isEmpty()&&sb4.isEmpty()&&sb5.isEmpty()&&sb6.isEmpty()&&sb7.isEmpty()&&sb8.isEmpty()&&sb9.isEmpty()){
            StringBuilder sb = new StringBuilder();
            sb.append("      无零值片。");
            createParagraph(sb.toString(),document);
        }else{
            if (!sb1.isEmpty()){
                StringBuilder sb = new StringBuilder();
                sb.append("      A相左串有").append(sb1.size()).append("片零值，分别是").append(listToString(sb1)).append("。\n");
                createParagraph(sb.toString(),document);
            }
            if (!sb2.isEmpty()){
                StringBuilder sb = new StringBuilder();
                sb.append("      A相中串有").append(sb2.size()).append("片零值，分别是").append(listToString(sb2)).append("。");
                createParagraph(sb.toString(),document);
            }
            if (!sb3.isEmpty()){
                StringBuilder sb = new StringBuilder();
                sb.append("      A相右串有").append(sb3.size()).append("片零值，分别是").append(listToString(sb3)).append("。");
                createParagraph(sb.toString(),document);
            }
            if (!sb4.isEmpty()){
                StringBuilder sb = new StringBuilder();
                sb.append("      B相左串有").append(sb4.size()).append("片零值，分别是").append(listToString(sb4)).append("。");
                createParagraph(sb.toString(),document);
            }
            if (!sb5.isEmpty()){
                StringBuilder sb = new StringBuilder();
                sb.append("      B相中串有").append(sb5.size()).append("片零值，分别是").append(listToString(sb5)).append("。");
                createParagraph(sb.toString(),document);
            }
            if (!sb6.isEmpty()){
                StringBuilder sb = new StringBuilder();
                sb.append("      B相右串有").append(sb6.size()).append("片零值，分别是").append(listToString(sb6)).append("。");
                createParagraph(sb.toString(),document);
            }
            if (!sb7.isEmpty()){
                StringBuilder sb = new StringBuilder();
                sb.append("      C相左串有").append(sb7.size()).append("片零值，分别是").append(listToString(sb7)).append("。");
                createParagraph(sb.toString(),document);
            }
            if (!sb8.isEmpty()){
                StringBuilder sb = new StringBuilder();
                sb.append("      C相中串有").append(sb8.size()).append("片零值，分别是").append(listToString(sb8)).append("。");
                createParagraph(sb.toString(),document);
            }
            if (!sb9.isEmpty()){
                StringBuilder sb = new StringBuilder();
                sb.append("      C相右串有").append(sb9.size()).append("片零值，分别是").append(listToString(sb9)).append("。");
                createParagraph(sb.toString(),document);
            }
        }
    }
    private void createParagraph(String string, XWPFDocument document){
        XWPFParagraph collectParagraph1 = document.createParagraph();
        collectParagraph1.setAlignment(ParagraphAlignment.LEFT);
        // 设置段落的行距为固定值（无行间距）
        CTP ctp = collectParagraph1.getCTP();
        CTPPr ctppr = ctp.getPPr() != null ? ctp.getPPr() : ctp.addNewPPr();
        CTSpacing spacing = ctppr.getSpacing() != null ? ctppr.getSpacing() : ctppr.addNewSpacing();

        // 设置行距为固定值 1 磅（几乎无间距）
        spacing.setLineRule(STLineSpacingRule.EXACT); // 固定值
        spacing.setLine(BigInteger.valueOf(280));

        XWPFRun run1 = collectParagraph1.createRun();
        run1.setText(string);
        run1.setFontSize(12);
    }
    private String listToString(List<Integer> list){
        if (list.isEmpty()){
            return "";
        }else{
            StringBuilder sb = new StringBuilder();
            for (int i = 0;i<list.size();i++){
                if (i == list.size()-1){
                    sb.append(list.get(i));
                }else{
                    sb.append(list.get(i)).append("、");
                }
            }
            return sb.toString();
        }
    }
}